import { ref, reactive } from 'vue'

class WebSocketManager {
  constructor() {
    this.ws = null
    this.connected = ref(false)
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 5000
    this.heartbeatInterval = 30000
    this.heartbeatTimer = null
    this.listeners = new Map()
    this.url = ''
  }

  // 连接WebSocket
  connect(url) {
    this.url = url
    
    try {
      this.ws = new WebSocket(url)
      this.setupEventHandlers()
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      this.handleReconnect()
    }
  }

  // 设置事件处理器
  setupEventHandlers() {
    this.ws.onopen = () => {
      console.log('WebSocket连接成功')
      this.connected.value = true
      this.reconnectAttempts = 0
      this.startHeartbeat()
      this.emit('connected')
    }

    this.ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data)
        this.handleMessage(data)
      } catch (error) {
        console.error('解析WebSocket消息失败:', error)
      }
    }

    this.ws.onclose = (event) => {
      console.log('WebSocket连接关闭:', event.code, event.reason)
      this.connected.value = false
      this.stopHeartbeat()
      this.emit('disconnected', { code: event.code, reason: event.reason })
      
      // 如果不是主动关闭，尝试重连
      if (event.code !== 1000) {
        this.handleReconnect()
      }
    }

    this.ws.onerror = (error) => {
      console.error('WebSocket错误:', error)
      this.emit('error', error)
    }
  }

  // 处理收到的消息
  handleMessage(data) {
    const { type, data: messageData } = data
    
    switch (type) {
      case 'log':
        this.emit('log', messageData)
        break
      case 'system':
        this.emit('system', messageData)
        break
      case 'connection_status':
        this.emit('connection_status', messageData)
        break
      default:
        this.emit('message', data)
    }
  }

  // 发送消息
  send(message) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(typeof message === 'string' ? message : JSON.stringify(message))
    } else {
      console.warn('WebSocket未连接，无法发送消息')
    }
  }

  // 断开连接
  disconnect() {
    if (this.ws) {
      this.ws.close(1000, '主动断开')
      this.ws = null
    }
    this.stopHeartbeat()
    this.connected.value = false
  }

  // 重连处理
  handleReconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
      
      setTimeout(() => {
        this.connect(this.url)
      }, this.reconnectInterval)
    } else {
      console.error('WebSocket重连失败，已达到最大重连次数')
      this.emit('reconnect_failed')
    }
  }

  // 开始心跳
  startHeartbeat() {
    this.heartbeatTimer = setInterval(() => {
      this.send({ type: 'heartbeat', timestamp: Date.now() })
    }, this.heartbeatInterval)
  }

  // 停止心跳
  stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer)
      this.heartbeatTimer = null
    }
  }

  // 添加事件监听器
  on(event, callback) {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, [])
    }
    this.listeners.get(event).push(callback)
  }

  // 移除事件监听器
  off(event, callback) {
    if (this.listeners.has(event)) {
      const callbacks = this.listeners.get(event)
      const index = callbacks.indexOf(callback)
      if (index !== -1) {
        callbacks.splice(index, 1)
      }
    }
  }

  // 触发事件
  emit(event, data) {
    if (this.listeners.has(event)) {
      this.listeners.get(event).forEach(callback => {
        try {
          callback(data)
        } catch (error) {
          console.error('事件回调执行错误:', error)
        }
      })
    }
  }

  // 获取连接状态
  isConnected() {
    return this.connected.value
  }
}

// 创建全局WebSocket管理器实例
export const wsManager = new WebSocketManager()

// 日志WebSocket连接
export const connectLogWebSocket = () => {
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  const host = window.location.host
  const wsUrl = `${protocol}//${host}/ws/logs`
  
  wsManager.connect(wsUrl)
  
  return wsManager
}

// 导出响应式状态
export const useWebSocket = () => {
  return {
    connected: wsManager.connected,
    connect: connectLogWebSocket,
    disconnect: () => wsManager.disconnect(),
    on: (event, callback) => wsManager.on(event, callback),
    off: (event, callback) => wsManager.off(event, callback),
    send: (message) => wsManager.send(message),
    isConnected: () => wsManager.isConnected()
  }
}
